<template>
  <div :style="style">
    <span class="image-box">
      <el-image
        v-if="imageUrl !== ''"
        hide-on-click-modal
        :src="imageUrl"
        style="width:100%;height:100%"
        fit="contain"
      />
    </span>
  </div>
</template>

<script setup>
import {ref, watch, computed, onMounted} from 'vue'
import api from "@/http/api";
import visual from "@/visual/js/visual";

const props = defineProps({
  node: Object,
  compStyle: Object,
  compData: Object,
});
const currNode = ref(props.node);
const loading = ref(true);
const message = ref('');
const imageUrl = ref('');

const loadValue = async() => {
  loading.value = false;
  message.value = '';
  imageUrl.value = '';

  const dataList = (await visual.loadData(props.compData, {}, {}, currNode.value)).data || [];
  currNode.value.compData.dataList = JSON.stringify(dataList);
  message.value = dataList.length > 0 && dataList[0]['内容'] || '二维码';
  loading.value = true;
  api.createQrCode(message.value).then((res) => {
    loading.value = false;
    imageUrl.value = URL.createObjectURL(new Blob([res.data]));
  }).catch(() => {
    loading.value = false;
  });
};

const style = computed(() => {
  const compStyle = props.compStyle || {};
  return `width: ${compStyle.width};height: ${compStyle.height}`;
});

watch(() => props.node.compData?.refresh, () => {
  loadValue();
});

onMounted(() => {
  loadValue();
});
</script>

<style scoped>
.image-box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.image-box img {
  max-width: 100%;
  max-height: 100%;
}
</style>